package com.hyacinth.common.framework;

import com.hyacinth.common.framework.i.IActionConstant;
import com.opensymphony.xwork2.Action;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.ServletActionContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.List;

public abstract class ActionSupport implements Action, Serializable, IActionConstant {

	private static final long serialVersionUID = -8306452161446192529L;

	protected static final ServletContext context = ServletActionContext.getServletContext();

	protected HttpServletRequest request = ServletActionContext.getRequest();

	protected HttpSession session = request.getSession();

	protected HttpServletResponse response = ServletActionContext.getResponse();

	protected static JsonConfig JsonConfig = null; // JsonConfig 单例,将过滤掉默认不需要的字段

	/**
	 * 获取JsonConfig,将过滤掉默认不需要的字段
	 * 
	 * @return
	 */
	protected JsonConfig getJsonConfig() {
        if (JsonConfig == null) {
			JsonConfig = new JsonConfig();
			JsonConfig.setExcludes(new String[] {});
		}
		return JsonConfig;
	}

	public String execute() throws Exception {
		return SUCCESS;
	}

	protected void printJsonList(List<?> list) throws Exception {
		JSONArray jsonArray = JSONArray.fromObject(list, getJsonConfig());
		printOut(jsonArray.toString().getBytes("utf-8"));
	}

	protected void printJsonObject(Object obj) throws Exception {
		JSONObject jsonObject = JSONObject.fromObject(obj, getJsonConfig());
		printOut(jsonObject.toString().getBytes("utf-8"));
	}

	protected void printOut(byte[] data) throws Exception {
		if (data == null)
			return;
		OutputStream os = null;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try {
			os = response.getOutputStream();
			os.write(data);
			os.flush();
		} catch (Exception e) {
			throw e;
		} finally {
			os.close();
		}
	}
	
	public String enter() throws Exception {
		return ENTER;
	}
	
	public String input() throws Exception {
		return INPUT;
	}
}
